import winreg

# 字符串， 32位值， 64位值
_supported_val_type = [winreg.REG_SZ, winreg.REG_DWORD, winreg.REG_QWORD]


def check_val_exist(branch, key, val_name):
    # check val exist or not in given branch with key
    try:
        reg_key = _read_key(branch, key)
        winreg.QueryValueEx(reg_key, val_name)
    except FileNotFoundError:
        return False
    return True


def get_machine_value(key, val_name):
    reg_key = _read_key(winreg.HKEY_LOCAL_MACHINE, key)
    return winreg.QueryValueEx(reg_key, val_name)


def get_current_user_value(key, val_name):
    reg_key = _read_key(winreg.HKEY_CURRENT_USER, key)
    return winreg.QueryValueEx(reg_key, val_name)


def set_or_delete_local_machine(key, val_name,  value, val_type):
    reg_key = _write_key(winreg.HKEY_LOCAL_MACHINE, key, value, val_type)
    if value is None:
        winreg.DeleteValue(reg_key, val_name)
    else:
        winreg.SetValueEx(reg_key, val_name, 0, val_type, value)
    winreg.CloseKey(reg_key)


def set_or_delete_current_user(key, val_name,  value, val_type):
    reg_key = _write_key(winreg.HKEY_CURRENT_USER, key, value, val_type)
    if value is None:
        winreg.DeleteValue(reg_key, val_name)
    else:
        winreg.SetValueEx(reg_key, val_name, 0, val_type, value)
    winreg.CloseKey(reg_key)


def _write_key(branch, key, value, val_type):
    if val_type is None and value is not None:
        raise Exception("val type and value must all None or nether None")
    if val_type is not None and val_type not in _supported_val_type:
        raise Exception("invalid val type %s" % val_type)
    key = key.replace("/", "\\")
    return winreg.OpenKey(branch, key, 0, winreg.KEY_SET_VALUE)


def _read_key(branch, key):
    key = key.replace("/", "\\")
    return winreg.OpenKey(branch, key, 0, winreg.KEY_READ)


if __name__ == '__main__':
    k = "SOFTWARE/7-zip"
    print(check_val_exist(winreg.HKEY_CURRENT_USER, k, "Path"))
#     k = r"SOFTWARE/7-zip"
#     print(get_machine_value(k, "Path64"))
#     try:
#         set_or_delete_local_machine(k, "tmp", "tmp", winreg.REG_SZ)
#         set_or_delete_local_machine(k, "tmp", None, None)
#         # disable windows defender
#         k = r"SOFTWARE\Policies\Microsoft\Windows Defender"
#         set_or_delete_local_machine(k, "DisableAntiSpyware", 1, winreg.REG_DWORD)
#         # disable windows firewall 4= close , 2= auto
#         k = r"SYSTEM\CurrentControlSet\Services\MpsSvc"
#         set_or_delete_local_machine(k, "Start", 4, winreg.REG_DWORD)
#         # disable windows error reporting
#         k = r"SOFTWARE\Microsoft\Windows\Windows Error Reporting"
#         set_or_delete_local_machine(k, "Disabled", 1, winreg.REG_DWORD)
#     except PermissionError:
#         print("admin permission required")
#     # install silent
#     # cmd start /wait  E:\7z-x64.exe /S /v/qn
# #     powershell

